<template>
  <div
    :class="$route.query.processInstanceId ? 'flow-container' : 'app-container'"
  >
    <div
      v-show="
        !modifyInfo.visible &&
        !detailInfo.visible &&
        !detailListInfo.visible &&
        !modifyReceiveInfo.visible &&
        !modifyByContractInfo.visible &&
        !buildAssetCardInfo.visible &&
        !modifySurplusInfo.visible &&
        !$route.query.processInstanceId &&
        !assetUseExportModifyInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-addReceive>
            <el-button @click="addReceive()">收货导入 </el-button>
          </template>
          <template v-slot:filter-addContract>
            <el-button @click="addContract()">合同导入 </el-button>
          </template>
          <template v-slot:filter-addSurplus>
            <el-button @click="addSurplus()">盘盈导入 </el-button>
          </template>
          <template v-slot:filter-assetUseExport>
            <el-button :disabled="canAssetUseExport" @click="assetUseExport()"
              >生成领用出库单</el-button
            >
          </template>
          <template v-slot:filter-submit>
            <el-button :disabled="canSubmit" @click="deviceSubmit()"
              >提交</el-button
            >
          </template>
          <template v-slot:filter-recall>
            <el-button :disabled="canRecall" @click="recall()">撤回</el-button>
          </template>
          <template v-slot:filter-buildCard>
            <el-button :disabled="!ifBuildCard" @click="buildListCard"
              >批量建卡</el-button
            >
          </template>
          <template v-slot:filter-generateInvoice>
            <el-button :disabled="!canGenerate" @click="generateInvoice()"
              >生成发票</el-button
            >
          </template>
          <template v-slot:filter-print>
            <el-button @click="print()">打印</el-button>
          </template>
          <template v-slot:filter-excel>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>
    <store-order-modify
      v-if="modifyInfo.visible"
      ref="modifyRef"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
      :flowFormType="flowFormType"
      @returnModify="returnModify"
    />
    <receive-modify
      v-if="modifyReceiveInfo.visible"
      ref="modifyRef"
      v-model:visible="modifyReceiveInfo.visible"
      :title="modifyReceiveInfo.title"
      :receive-order="modifyReceiveInfo.receiveOrder"
      :order-id="modifyReceiveInfo.orderId"
      :flowFormType="flowFormType"
      @returnModify="returnModify"
    />
    <contract-modify
      v-if="modifyByContractInfo.visible"
      ref="modifyRef"
      v-model:visible="modifyByContractInfo.visible"
      :title="modifyByContractInfo.title"
      :contract-order="modifyByContractInfo.contractOrder"
      :order-id="modifyByContractInfo.orderId"
      :flowFormType="flowFormType"
      @returnModify="returnModify"
    />
    <modify-surplus
      v-if="modifySurplusInfo.visible"
      ref="modifyRef"
      v-model:visible="modifySurplusInfo.visible"
      :orderId="modifySurplusInfo.id"
      :surplusId="modifySurplusInfo.surplusId"
      :surplusNo="modifySurplusInfo.surplusNo"
      :title="modifySurplusInfo.title"
      :type="''"
      :flowFormType="flowFormType"
      @returnModify="returnModify"
    />
    <store-order-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio label="page">当前页数据</el-radio>
          <el-radio label="all">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>

    <chose-printer :visible="printerInfo.visible" @callBack="printerCallBack" />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <!--选择收货单-->
    <selectReceive
      v-if="receiveInfo.visible"
      v-model:show-dialog="receiveInfo.visible"
      :show-price="$permission('assetStoreOrder:price')"
      :highlight-row="true"
      :check-box="false"
      :check-lock="true"
      :query="receiveInfo.query.queryMap"
      :save-empty="false"
      @callback="_selectReceive"
    />
    <!--选择合同-->
    <select-contract
      v-if="contractInfo.visible"
      v-model:visible="contractInfo.visible"
      :query="contractInfo.query"
      @callback="selectContractBack"
    />
    <!--选择盘盈单-->
    <select-surplus
      v-if="surplusInfo.visible"
      v-model:showDialog="surplusInfo.visible"
      :highlightRow="true"
      :checkBox="false"
      :query="surplusInfo.query"
      @callback="selectSurplusInfoBack"
    />
    <!-- 入库选择弹窗 -->
    <auto-build-card
      v-if="buildCardDialogInfo.visible"
      :show-dept="false"
      v-model:show-dialog="buildCardDialogInfo.visible"
      @updateFormInfo="updateFormInfo"
    ></auto-build-card>
    <!-- 批量建卡 -->
    <BuildAssetCard
      v-if="buildAssetCardInfo.visible"
      v-model:visible="buildAssetCardInfo.visible"
      :tableRow="buildAssetCardInfo.tableRow"
      :currentAccountingInterval="buildAssetCardInfo.currentAccountingInterval"
      :type="buildAssetCardInfo.type"
      @returnModify="getList"
    ></BuildAssetCard>
    <AssetUseExportModify
      v-if="assetUseExportModifyInfo.visible"
      v-model:visible="assetUseExportModifyInfo.visible"
      :title="assetUseExportModifyInfo.title"
      :otherFormData="assetUseExportModifyInfo.otherFormData"
    />
    <!-- 生成发票 -->
    <PageDialog
      v-show="generateInvoiceInfo.visible"
      :title="generateInvoiceInfo.title"
      v-model:visible="generateInvoiceInfo.visible"
      :width="generateInvoiceInfo.width"
      :bt-loading="generateInvoiceInfo.btLoading"
      :bt-list="generateInvoiceInfo.btList"
    >
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="generateInvoiceInfo.formInfo.ref"
        :data="generateInvoiceInfo.formInfo.data"
        :field-list="generateInvoiceInfo.formInfo.fieldList"
        :rules="generateInvoiceInfo.formInfo.rules"
        :label-width="generateInvoiceInfo.formInfo.labelWidth"
      >
        <template v-slot:form-invoiceDate="scope">
          <el-date-picker
            v-model="generateInvoiceInfo.formInfo.data.invoiceDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
          />
        </template>
      </PageForm>
    </PageDialog>
  </div>
</template>

<script setup name="assetStore">
import {
  getAssetStoreOrderCustomizeList,
  removeAssetStoreOrder,
  submitAssetStoreOrder,
  revokeAssetStoreOrder,
  storeAssetStoreOrder,
  excelForListAssetStoreOrders,
  printForListAssetStoreOrders,
  assetStoreOrdersBuild,
  approvedAssetStore,
  refuseAssetStore,
  rejectAssetStore,
  cancelCheckStoreOrder,
  batchBuildByAssetStoreOrders,
  createInvoiceOrders,
  detailAssetStoreOrder,
} from '@/api/asset.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getDepotAll, getCurrentFiscalPeriod } from '@/api/core'
import { getBusinessKeyById } from '@/api/flowable'
import { fatchTemplateByCode } from '@/api/base'
const SelectContract = defineAsyncComponent(() =>
  import('@/components/SelectContractStore/index')
)
const selectReceive = defineAsyncComponent(() => import('./selectReceive'))
const detailList = defineAsyncComponent(() => import('./detailList'))
const storeOrderModify = defineAsyncComponent(() => import('./modify'))
const receiveModify = defineAsyncComponent(() => import('./modifyReceive'))
const selectSurplus = defineAsyncComponent(() => import('./selectSurplus'))
const contractModify = defineAsyncComponent(() => import('./modifyContract'))
const modifySurplus = defineAsyncComponent(() => import('./modifySurplus'))
const storeOrderDetail = defineAsyncComponent(() => import('./detail'))
const AutoBuildCard = defineAsyncComponent(() =>
  import('@/views/asset/components/autoBuildCard')
)
const AssetUseExportModify = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetUseExport/modify')
)
import moment from 'moment'
import { ElLoading, ElMenu } from 'element-plus'
import { defineAsyncComponent } from 'vue'

const props = defineProps(['id'])
const { proxy } = getCurrentInstance()
const route = useRoute()
const generateInvoiceInfo = reactive({
  visible: false,
  title: '生成发票',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseBtnGenerate, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveBtnGenerate,
      show: true,
    },
  ],
  formInfo: {
    ref: null,
    data: {
      invoiceDate: moment(new Date()).format('YYYY-MM-DD'),
    },
    fieldList: [
      { label: '开票日期', value: 'invoiceDate', type: 'slot' },
      { label: '纸质发票号', value: 'invoiceNumber', type: 'input' },
      { label: '合同号', value: 'contractNumber', type: 'input' },
    ],
    rules: {
      invoiceDate: [
        { required: true, message: '请选择开票日期', trigger: 'change' },
      ],
      invoiceNumber: [
        { required: true, message: '请输入纸质发票号', trigger: 'blur' },
      ],
      /* contractNumber: [
        { required: true, message: '请输入合同号', trigger: 'blur' },
      ], */
    },
    labelWidth: '120px',
  },
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'asset_store_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('assetStoreOrder:add'),
    },
    {
      type: 'slot',
      value: 'addReceive',
      show: proxy.$permission('assetStoreOrder:addReceive'),
    },
    {
      type: 'slot',
      value: 'addContract',
      show: proxy.$permission('assetStoreOrder:addContract'),
    },
    {
      type: 'slot',
      value: 'addSurplus',
      show: proxy.$permission('assetStoreOrder:addContract'),
    },
    {
      type: 'slot',
      value: 'assetUseExport',
      show: proxy.$permission('assetStoreOrder:assetUseExport'),
    },
    {
      type: 'slot',
      value: 'submit',
      show: proxy.$permission('assetStoreOrder:submit'),
    },
    {
      type: 'slot',
      value: 'store',
      show: proxy.$permission('assetStoreOrder:store'),
    },
    {
      type: 'slot',
      value: 'recall',
      show: proxy.$permission('assetStoreOrder:recall'),
    },
    {
      type: 'slot',
      value: 'buildCard',
      show:
        proxy.$permission('assetStore:buildCard') &&
        proxy.$store.state.permission.systemConfig.auto_build_card == 0,
    },
    {
      type: 'slot',
      value: 'printQrCode',
      show: proxy.$permission('assetStoreOrder:printCode'),
    },
    { type: 'slot', value: 'upload' },
    {
      type: 'slot',
      value: 'generateInvoice',
      show: true,
      //show: proxy.$permission('assetStoreOrder:generateInvoice'),
    },
    {
      type: 'slot',
      value: 'excel',
      show: proxy.$permission('assetStoreOrder:excelList'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('assetStoreOrder:printList'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: deviceSubmit,
        show: proxy.$permission('assetStoreOrder:submit'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 7
        },
      },
      {
        label: '批量建卡',
        event: buildListCard,
        show:
          proxy.$permission('assetStore:buildCard') &&
          proxy.$store.state.permission.systemConfig.auto_build_card == 0,
        ifRender: function (row) {
          return row.buildCardStatus === 1 || row.buildCardStatus === 2
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('assetStoreOrder:update'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 7
        },
      },
      {
        label: '批准',
        event: approve,
        show: proxy.$permission('assetStoreOrder:approve'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('assetStoreOrder:reject'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '拒绝',
        event: refuse,
        show: proxy.$permission('assetStoreOrder:refuse'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '销审',
        event: salesReview,
        show: proxy.$permission('assetStoreOrder:salesReview'),
        ifRender: checkIfRenderSalesReview,
      },
      {
        label: '撤回',
        event: recall,
        show: proxy.$permission('assetStoreOrder:recall'),
        ifRender: checkIfRenderRecall,
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('assetStoreOrder:delete'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 7
        },
      },
    ],
  },
})
const receiveInfo = ref({
  visible: false,
  query: {
    queryMap: {},
  },
})
const contractInfo = ref({
  visible: false,
  query: {
    contractType: 1,
    sourceType: 2,
  },
})
const surplusInfo = ref({
  visible: false,
  query: {},
})
const modifyInfo = ref({
  visible: false,
  orderId: '',
  title: '',
})
const modifyReceiveInfo = ref({
  visible: false,
  orderId: '',
  receiveOrder: {},
  title: '',
})
const modifyByContractInfo = ref({
  visible: false,
  orderId: '',
  contractOrder: {
    sourceType: 2,
  },
  title: '',
})
const modifySurplusInfo = ref({
  visible: false,
  id: '',
  surplusId: '',
  title: '',
  surplusNo: '',
})
const detailInfo = ref({
  visible: false,
  data: {},
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const buildAssetCardInfo = ref({
  visible: false,
  tableRow: [],
  type: '',
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const time = ref([])
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: 'page',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const formInfoData = ref({})
const buildCardDialogInfo = ref({
  visible: false,
  type: '',
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const assetUseExportModifyInfo = ref({
  visible: false,
  otherFormData: {},
  title: '新增出库单',
})

// 生成领用出库单
const canAssetUseExport = computed(() => {
  // 勾选的入库单，如果入库仓库是同一个，并且建卡状态为部分建卡或者完全建卡，可以点击生成领用出库单按钮，
  if (tableInfo.value.selections.length === 0) {
    return true
  }
  const buildCardStatusArr = [2, 3]
  const firstDepotId = tableInfo.value.selections[0].depotId
  const tempBool = tableInfo.value.selections.some((item) => {
    if (
      !buildCardStatusArr.includes(item.buildCardStatus) ||
      item.depotId !== firstDepotId
    ) {
      return true
    }
  })
  return tempBool
})
// 批量审批（选中的数据全是未提交或者全是已驳回）
const canSubmit = computed(() => {
  if (
    tableInfo.value.selections.length === 0 ||
    !proxy.$permission('assetStoreOrder:submit')
  ) {
    return true
  }
  const statusArr = [1, 7]
  const tempBool = tableInfo.value.selections.some((item) => {
    if (!statusArr.includes(item.status)) {
      return true
    }
  })
  return tempBool
})
const canRecall = computed(() => {
  if (!tableInfo.value.selections.length) {
    return true
  }
  const tempBool = tableInfo.value.selections.some((item) => {
    if (
      (item.status === 3 &&
        proxy.$store.state.permission.systemConfig
          .allow_assets_store_approval == 0) ||
      item.status === 4
    ) {
      return false
    } else {
      return true
    }
  })
  return tempBool
})
const canPrintQrCode = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter(
      (item) => item.status !== 2 && item.status !== 3
    ).length
  )
})
const ifBuildCard = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.length ===
      tableInfo.value.selections.filter(
        (item) => item.buildCardStatus === 1 || item.buildCardStatus === 2
      ).length
  )
})
const canGenerate = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.length ===
      tableInfo.value.selections.filter((item) => item.status === 3).length
  )
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
const flowFormType = ref('')

watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

onMounted(() => {
  if (proxy.$route.query.processInstanceId) {
    detailAssetStoreOrder(props.id).then((resp) => {
      if (resp && resp.success) {
        toModify(resp.data)
        flowFormType.value = 'defaultFlowType'
      }
    })
  } else {
    flowFormType.value = ''
  }
})
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'assetStore' && el.url === val.url) {
                detailListInfo.value.visible = false
                modifyInfo.value.visible = false
                modifyByContractInfo.value.visible = false
                modifyReceiveInfo.value.visible = false
                modifySurplusInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.id = val.businessId
                    sessionStorage.setItem('storeRowId', val.businessId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
// 外部流程组件也需调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  proxy.$refs['modifyRef'].save(isSaveAndSubmit, obj)
}
function update(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'assetStore',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        toModify(row)
      }
    }
  })
}
function toModify(row) {
  if (row.receiveId && row.receiveId !== -2) {
    modifyReceiveInfo.value.orderId = row.id
    modifyReceiveInfo.value.title = '修改入库单'
    modifyReceiveInfo.value.visible = true
    modifyReceiveInfo.value.receiveOrder = { id: row.receiveId }
  } else if (row.contractId && row.contractId !== -2) {
    modifyByContractInfo.value.orderId = row.id
    modifyByContractInfo.value.title = '修改入库单'
    modifyByContractInfo.value.visible = true
    modifyByContractInfo.value.contractOrder = { id: row.contractId }
  } else if (row.sourceType === 52) {
    modifySurplusInfo.value.visible = true
    modifySurplusInfo.value.id = row.id
    modifySurplusInfo.value.surplusId = row.sourceId
    modifySurplusInfo.value.surplusNo = row.sourceOrderNo
    modifySurplusInfo.value.title = '修改入库单'
  } else {
    modifyInfo.value.orderId = row.id
    modifyInfo.value.title = '修改入库单'
    modifyInfo.value.visible = true
  }
}
function generateInvoice() {
  generateInvoiceInfo.visible = true
}
function saveBtnGenerate() {
  generateInvoiceInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      let ids = tableInfo.value.selections.map((element) => {
        return element.id
      })
      createInvoiceOrders({ ids, ...generateInvoiceInfo.formInfo.data }).then(
        (resp) => {
          if (resp && resp.success) {
            search()
          }
          handleCloseBtnGenerate()
        }
      )
    }
  })
}
function handleCloseBtnGenerate() {
  generateInvoiceInfo.visible = false
  generateInvoiceInfo.formInfo.data = {
    invoiceDate: moment(new Date()).format('YYYY-MM-DD'),
  }
  proxy.$nextTick(() => {
    generateInvoiceInfo.formInfo.ref.clearValidate()
  })
}
// 批准/拒绝
function checkIfRenderBtnFlow(row) {
  return (
    proxy.$store.state.permission.systemConfig.allow_assets_store_approval ==
      1 && row.status === 4
  )
}
// 销审
function checkIfRenderSalesReview(row) {
  return (
    row.status === 3 &&
    proxy.$store.state.permission.systemConfig.allow_assets_store_approval != 0
  )
}
// 撤回
function checkIfRenderRecall(row) {
  return (
    row.status === 4 ||
    (row.status === 3 &&
      proxy.$store.state.permission.systemConfig.allow_assets_store_approval ==
        0)
  )
}
setData()
function setData() {
  let obj = {
    typeValue: {
      label: '养护类型',
      value: 'typeValue',
      asValue: 'type',
      componentType: 'select-model',
      code: 'device_maintenance_type',
      show: false,
      hidden: true,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'asset_store_order_status',
      show: false,
      hidden: true,
    },
    receiveOrderNo: {
      label: '收货单号',
      value: 'receiveNo',
      componentType: 'input',
      show: false,
      hidden: true,
    },
    depotName: {
      label: '出库仓库',
      value: 'depotName',
      asValue: 'depotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '2',
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function pageInfo(obj) {
  page.value = obj
}
function handleClose() {
  dialogInfo.value.visible = false
}
function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = 'page'
}
function exportExcelList() {
  if (dialogInfo.value.flag === 'select') {
    if (!tableInfo.value.selections.length) {
      proxy.$message.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
  }
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag === 'page' ? true : false,
  }

  excelForListAssetStoreOrders(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = 'page'
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'assetStoreOrder:printList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  if (dialogInfo.value.flag === 'select') {
    if (!tableInfo.value.selections.length) {
      proxy.$message.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
  }
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag === 'page' ? true : false,
  }
  printForListAssetStoreOrders(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function addReceive() {
  receiveInfo.value.visible = true
}
function _selectReceive(row) {
  modifyReceiveInfo.value.orderId = ''
  modifyReceiveInfo.value.receiveOrder = row
  modifyReceiveInfo.value.visible = true
  modifyReceiveInfo.value.title = '根据收货单导入'
}
function addContract() {
  contractInfo.value.visible = true
}
function selectContractBack(data) {
  proxy.$nextTick(() => {
    if (data && data.id) {
      modifyByContractInfo.value.visible = true
      modifyByContractInfo.value.contractOrder = data
      modifyByContractInfo.value.orderId = ''
      modifyByContractInfo.value.title = '新增入库单'
    }
  })
}
function addSurplus() {
  surplusInfo.value.visible = true
}
function assetUseExport() {
  assetUseExportModifyInfo.value.visible = true
  assetUseExportModifyInfo.value.otherFormData = tableInfo.value.selections[0]
  assetUseExportModifyInfo.value.otherFormData.ids =
    tableInfo.value.selections.map((item) => item.id)
}
function selectSurplusInfoBack(data) {
  proxy.$nextTick(() => {
    if (data && data.id) {
      modifySurplusInfo.value.visible = true
      modifySurplusInfo.value.surplusId = data.id
      modifySurplusInfo.value.surplusNo = data.orderNo
      modifySurplusInfo.value.id = ''
      modifySurplusInfo.value.title = '新增入库单'
    }
  })
}
function returnModify() {
  if (modifyInfo.value.orderId) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'asset_store_order',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
function showDialog(row) {
  if (row && row.id) {
    buildAssetCardInfo.value.tableRow = [row]
  } else {
    buildAssetCardInfo.value.tableRow = tableInfo.value.selections
  }
  getCurrentFiscalPeriod(2).then((resp) => {
    if (resp && resp.success && resp.data) {
      buildAssetCardInfo.value.currentAccountingInterval = resp.data.startDate
    }
  })
  buildAssetCardInfo.value.type = 'store-store'
  buildAssetCardInfo.value.visible = true
}
function updateFormInfo(val) {
  if (val) {
    formInfoData.value = Object.assign(formInfoData.value, val)
  }
  buildCard()
}
function buildListCard(row = undefined) {
  //批量建卡
  if (row && row.id) {
    buildAssetCardInfo.value.tableRow = [row]
  } else {
    buildAssetCardInfo.value.tableRow = tableInfo.value.selections
  }
  let ids = buildAssetCardInfo.value.tableRow.map((element) => {
    return element.id
  })
  batchBuildByAssetStoreOrders(ids).then((res) => {
    if (res.success) {
      search()
    }
  })
  /* getCurrentFiscalPeriod(2).then((resp) => {
    if (resp && resp.success && resp.data) {
      buildAssetCardInfo.value.currentAccountingInterval = resp.data.startDate
    }
  })
  buildAssetCardInfo.value.type = 'store-build'
  buildAssetCardInfo.value.visible = true */
}
function buildCard() {
  const params = {
    ...formInfoData.value,
  }
  const api =
    buildCardDialogInfo.value.type === 'store'
      ? storeAssetStoreOrder
      : buildCardDialogInfo.value.type === 'build'
      ? assetStoreOrdersBuild
      : ''
  api(params).then((res) => {
    if (res && res.success) {
      buildCardDialogInfo.value.visible = false
      formInfoData.value = {}
      getList()
    }
  })
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  removeAssetStoreOrder(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//创建
function create() {
  modifyInfo.value.orderId = ''
  modifyInfo.value.title = '新增入库单'
  modifyInfo.value.visible = true
}
// 审核通过
function approve(row) {
  approvedAssetStore({ orderId: row.id }).then((resp) => {
    if (resp && resp.success) {
      search()
    }
  })
}
function reject(row) {
  btnFlow(row, 'reject')
}
function refuse(row) {
  btnFlow(row, 'refuse')
}
// 按钮审批原因弹窗
function btnFlow(row, code) {
  let currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAssetStore
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAssetStore
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          search()
        }
      })
    })
}
function salesReview(row) {
  cancelCheckStoreOrder([row.id]).then((res) => {
    if (res && res.success) {
      getList()
      proxy.$message.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      proxy.$message.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}

function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
//提交
function deviceSubmit(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'assetStore',
    orderIds: ids,
  }
  submitAssetStoreOrder(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function assetStore(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push({ orderSourceId: row.id })
  } else {
    ids = tableInfo.value.selections.map((item) => {
      return {
        orderSourceId: item.id,
      }
    })
  }
  storeAssetStoreOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function recall(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  revokeAssetStoreOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function beforeUpload() {
  //导入
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
//展示明细
function showDetail(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'assetStore',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.value.data = row
        detailInfo.value.visible = true
      }
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetStoreOrderList-com.slip.spd.entity.vo.device.store.AssetStoreOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getAssetStoreOrderCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped>
.flow-container {
  height: calc(100vh - 164px);
}
</style>
